package com.faf.ui;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.faf.dao.impl.UserDaoImpl;
import com.faf.tools.RSAUtils;

/**
 * Servlet implementation class UserUpdatePwd
 */
@WebServlet("/UserUpdatePwd")
public class UserUpdatePwd extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserUpdatePwd() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//设置session
		HttpSession session = request.getSession();
		//设置中文格式
		response.setContentType("text/html;charset=utf-8"); 
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//获取密码
		String account = (String) session.getAttribute("account");
		String newpwd = request.getParameter("newpwd");
		String newcpwd = request.getParameter("newcpwd");
		
		String password = request.getParameter("password");
		password = RSAUtils.publicEncrytype(password);
		String pwd_rsa = RSAUtils.privateDecrypt(password);
		String sql_pwd = "update user set userPassword=? where userNumber=? ";
		String json = null;
		System.out.println("pwd");
		//查询
		UserDaoImpl user = new UserDaoImpl();
		try {
			if(pwd_rsa.equals(RSAUtils.privateDecrypt(user.getUserByNumber(account).getUserPassword()))){//和原密码一致
				
				if(newpwd.equals(newcpwd)){
					json = "{\"code\":"+1+"}";
					System.out.println(pwd_rsa+"两次密码一致"+newpwd);
					
					user.executeUpdate(sql_pwd, RSAUtils.publicEncrytype(newpwd),account);//更新用户信息的数据库
					session.setAttribute("account",account);
					
					System.out.println("密码更新成功");
					//更新之后保留页面内容
					response.getWriter().print(json);
				}
				else{
					json = "{\"code\":"+0+"}";
					System.out.println("两次密码不一致");
					response.getWriter().print(json);
				}
			}
			else{
				json = "{\"code\":"+-1+"}";
				System.out.println("和原密码不一致");
				System.out.println(password+RSAUtils.privateDecrypt(user.getUserByNumber(account).getUserPassword()));
				response.getWriter().print(json);
			}
			//更新之后保留页面内容
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("更新失败");
		} 
	}

}
